<template>
  <el-card>
    <!-- 以下是搜索栏 -->
    <el-row justify="space-between">
      <el-col :span="16" style="margin-bottom: 15px">
        <!-- 搜索条件form，按“搜索”按钮，搜索 -->
        <el-form inline :model="searchParams">
          <el-form-item label="菜品分类">
            <el-select
              v-model="searchParams.categoryId"
              placeholder="全部"
              style="min-width: 160px"
            >
              <el-option label="全部" value="" />
              <el-option
                :label="category.name"
                :value="category.id"
                v-for="category in categoryList"
                :key="category.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="菜品名称">
            <el-input
              v-model="searchParams.name"
              placeholder="请输入菜品名称"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getDishList()">搜索</el-button>
            <el-button type="info" @click="goReset()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <!-- 新增菜品按钮，按此按钮打开对话框 -->
        <el-button type="primary" @click="onAddDish()"> + 新增菜品 </el-button>
        <el-button type="success" @click="onSaleStatusBatch(1)">
          批量起售
        </el-button>
        <el-button type="info" @click="onSaleStatusBatch(0)">
          批量停售
        </el-button>
      </el-col>
    </el-row>

    <!-- 以下是展示菜品的表格 -->
    <el-row>
      <el-col>
        <el-table
          :data="dishList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="菜品名称"
            width="200"
            prop="name"
          ></el-table-column>
          <el-table-column
            label="所属分类"
            width="120"
            prop="categoryName"
          ></el-table-column>
          <el-table-column prop="type" label="分类类型">
            <template v-slot="scope">
              <el-tag :type="scope.row.type == '1' ? 'primary' : 'success'">{{
                scope.row.type == '1' ? '套餐' : '菜品'
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="菜品图片">
            <template #default="scope">
              <el-image
                style="width: 55px; height: 55px"
                :src="'/api/common/download?name=' + scope.row.image"
                fit="fill"
                :preview-src-list="[
                  '/api/common/download?name=' + scope.row.image
                ]"
                :preview-teleported="true"
              />
              <!-- 给el-image 加上 :preview-teleported="true" 解决遮罩层盖不住table的问题  -->
            </template>
          </el-table-column>
          <el-table-column prop="price" label="菜品价格">
            <template #default="scope">
              <strong>&yen; {{ Number(scope.row.price / 100) }}</strong>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="销售状态" align="center">
            <template #default="scope">
              <!-- 这里只提供展示，不支持切换销售状态 -->
              <el-switch
                disabled
                v-model="scope.row.status"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="起售"
                inactive-text="停售"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="操作时间"
            align="center"
            width="180px"
          >
            <template #default="scope">
              {{ scope.row.updateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180px">
            <template #default="scope">
              <el-button type="primary" @click="onEditDish(scope.row)">
                修改
              </el-button>
              <el-button type="danger" @click="onDeleteDish(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 以下是分页组件 -->
    <el-row>
      <el-col>
        <el-pagination
          style="margin-top: 15px"
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </el-card>

  <!-- 新增、编辑菜品的组件（对话框）  -->
  <dish-add-edit
    ref="dishAddEditRef"
    @update-dish-success="getDishList"
  ></dish-add-edit>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { reqDishList } from '@/api/dish'
import { reqGetCategoryListNoPage } from '@/api/category'
import DishAddEdit from '@/views/dish/DishAddEdit.vue'

// 菜品列表
const dishList = ref([])

//分页
const total = ref(0)

//搜索
const searchParams = ref({
  page: 1,
  pageSize: 5,
  name: '',
  categoryId: ''
})

const getDishList = async () => {
  const res = await reqDishList(searchParams.value)
  // console.log(res)
  dishList.value = res.data.data.records
  total.value = res.data.data.total
}

onMounted(() => {
  getDishList()
  getCategoryListNoPage() //不分页获取所有菜品(type=1)的分类
})

//method:分页功能
const handleSizeChange = (val) => {
  searchParams.value.pageSize = val
  getDishList()
}
const handleCurrentChange = (val) => {
  searchParams.value.page = val
  getDishList()
}

//搜索功能
const categoryList = ref([])

//不分页获取所有菜品(type=1)的分类
const getCategoryListNoPage = async () => {
  const res = await reqGetCategoryListNoPage({ type: 1 })
  // console.log(res)
  categoryList.value = res.data.data
}

//重置表单
const goReset = () => {
  searchParams.value = {
    page: 1,
    pageSize: 5,
    name: '',
    categoryId: ''
  }
  getDishList()
}

// 打开：新增、编辑菜品的对话框
const dishAddEditRef = ref(null)

const onAddDish = () => {
  dishAddEditRef.value.open({})
}

const onEditDish = (dish) => {
  dishAddEditRef.value.open(dish)
}

// 处理表格多选
const dishIdSelections = ref([])
const handleSelectionChange = (items) => {
  console.log(items)
  // items中是包含了多个dish数据的数组，
  // 下面将从items中取出每个dish的id存入dishMultiSelection中
  dishIdSelections.value = []
  items.forEach((item) => {
    dishIdSelections.value.push(item.id)
  })
  // console.log(dishIdSelections.value);
}

import { reqUpdateDishStatusBatch } from '@/api/dish'
import { ElMessage } from 'element-plus'

// 批量起售、停售的函数
const onSaleStatusBatch = async (statusValue) => {
  if (dishIdSelections.value.length > 0) {
    const res = await reqUpdateDishStatusBatch(
      statusValue,
      dishIdSelections.value
    )
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || '修改成功')
      //重新获取列表
      getDishList()
    }
  }
}

//删除菜品
import { ElMessageBox } from 'element-plus'
import { reqDeleteDish } from '@/api/dish'
const onDeleteDish = (dish) => {
  ElMessageBox.confirm(`确定要删除菜品[${dish.name}]?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDeleteDish(dish.id)
      ElMessage({
        type: 'success',
        message: dish.name + '删除成功'
      })
      getDishList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
</script>

<style scoped></style>
